package com.czl.module_service.viewmodel

import android.os.Bundle
import android.text.format.DateUtils
import android.util.Log
import androidx.databinding.ObservableField
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.TimeUtils
import com.czl.base.base.BaseBean
import com.czl.base.base.BaseViewModel
import com.czl.base.base.MyApplication
import com.czl.base.binding.command.BindingAction
import com.czl.base.binding.command.BindingCommand
import com.czl.base.config.AppConstants
import com.czl.base.data.DataRepository
import com.czl.base.data.bean.ImgRspBean
import com.czl.base.data.bean.tengyun.*
import com.czl.base.event.AddAssetHanldeSortSelectEvent
import com.czl.base.event.LiveBusCenter
import com.czl.base.event.SingleLiveEvent
import com.czl.base.extension.ApiSubscriberHelper
import com.czl.base.util.RxThreadHelper
import com.jeremyliao.liveeventbus.LiveEventBus
import java.util.*
import kotlin.collections.ArrayList

class AssetHandleApplyAddViewModel(application: MyApplication, model: DataRepository) :
    BaseViewModel<DataRepository>(application, model) {

    val uc = UiChangeEvent()

    var entityBean = AssetHandleBean()
    val facilityList: MutableList<AssetHandleFacilityBean> = arrayListOf()
    var inUseLowerList: MutableList<AssetHandleSortBean> = arrayListOf()
    var inStoreLowerList: MutableList<AssetHandleSortBean> = arrayListOf()
    var inUseProductList: MutableList<AssetHandleSortBean> = arrayListOf()
    var inStoreProductList: MutableList<AssetHandleSortBean> = arrayListOf()
    var fileList: MutableList<FileBean> = arrayListOf()
    var fileParamUrl = ObservableField("")
    var isScan = ObservableField(true)

    var faceUrl = ObservableField("")
    var entityBeanNote = ObservableField("")
    var facilityIdNum = ObservableField("")
    var facilityIdList: ArrayList<Int> = arrayListOf()
    var productIdList: ArrayList<Int> = arrayListOf()
    var inDamageLowerIdList: ArrayList<String> = arrayListOf()
    var inInventoryLowerIdList: ArrayList<String> = arrayListOf()
    var sortIdInfoList: HashMap<String, Int> = hashMapOf()
    var facilityTypeStr = ObservableField("请选择资产类型")
    var ownerCompanyStr = ObservableField("请选择产权公司")
//    var facilityType: Int? = null

    class UiChangeEvent {
        val choiceImgEvent: SingleLiveEvent<Int> = SingleLiveEvent()
        val clearFacilityListEvent: SingleLiveEvent<Int> = SingleLiveEvent()
        val clearLowerListEvent: SingleLiveEvent<Int> = SingleLiveEvent()
        val choiceFacilityTypeEvent: SingleLiveEvent<Any> = SingleLiveEvent()
        val choiceOwnerCompanyEvent: SingleLiveEvent<Any> = SingleLiveEvent()
        val choiceOwnerCompanyListEvent: SingleLiveEvent<ListBean<CompanyBean>> = SingleLiveEvent()
        val choiceAdapterFileEvent: SingleLiveEvent<ImgRspBean> = SingleLiveEvent()
    }

    val onImageClick: BindingCommand<Any> = BindingCommand(BindingAction {
        uc.choiceImgEvent.postValue(MODEL_IMG)
    })

    val onSubmitClickCommand: BindingCommand<Any> = BindingCommand(BindingAction {
//        LiveBusCenter.postGoToTabEvent(1)
        if (checkBeanInfo()) {
            return@BindingAction
        }
        if (checkListInfo()) {
            return@BindingAction
        }
        entityBean.note = entityBeanNote.get()
        if (entityBean.facilityType == 0) {
            entityBean.facilityList = facilityList
        } else {
            entityBean.inUseLowerList = inUseLowerList
            entityBean.inStroreLowerList = inStoreLowerList
            entityBean.inUseProductList = inUseProductList
            entityBean.inStroreProductList = inStoreProductList
        }
        entityBean.applicationName = TimeUtils.date2String(
            Date(),
            "yyyyMMdd"
        ) + model.getLocalUserInfo()?.userName + "提交的" + facilityTypeStr.get() + "申请"
        entityBean.applicationCompanyId = model.getLocalUserInfo()?.companyId
        entityBean.applicationUserId = model.getLocalUserInfo()?.userId
        entityBean.file = fileList

//        Log.e(">>>", GsonUtils.getGson().toJson(entityBean))
        addApply()
    })
    val onHandleClick: BindingCommand<Any> = BindingCommand(BindingAction {
        if (checkBeanInfo()) {
            return@BindingAction
        }
        if (entityBean.facilityType == 0) {
            startContainerActivity(
                AppConstants.Router.Service.F_SERVICE_ASSET_HANDLE_FACILITY, Bundle().apply {
                    putSerializable("parentCompanyId", entityBean.parentCompanyId)
                    putIntegerArrayList("facilityIdList", facilityIdList)
                })
        } else {
            startContainerActivity(
                AppConstants.Router.Service.F_SERVICE_ASSET_HANDLE_SORT, Bundle().apply {
                    putSerializable("parentCompanyId", entityBean.parentCompanyId)
                    putIntegerArrayList("productIdList", productIdList)
                    putStringArrayList("inDamageLowerIdList", inDamageLowerIdList)
                    putStringArrayList("inInventoryLowerIdList", inInventoryLowerIdList)
                })
            LiveBusCenter.postAddAssetHanldeSortSelectEvent(sortIdInfoList)
        }
    })

    val getFacilityTpyeInfo: BindingCommand<Any> = BindingCommand(BindingAction {
        uc.choiceFacilityTypeEvent.postValue(0)
    })
    val getOwerCompanyInfo: BindingCommand<Any> = BindingCommand(BindingAction {
        uc.choiceOwnerCompanyEvent.postValue(0)
    })

    companion object {
        const val MODEL_IMG = 100
        const val ADAPTER_IMG = 101
    }

    fun uploadHeadImg(imgSrc: String, type: Int) {
        model.apply {
            uploadHeadImg("szchd", imgSrc, "assets")
                .compose(RxThreadHelper.rxSchedulerHelper(this@AssetHandleApplyAddViewModel))
                .doOnSubscribe { showLoading() }
                .subscribe(object : ApiSubscriberHelper<BaseBean<ImgRspBean>>() {
                    override fun onResult(t: BaseBean<ImgRspBean>) {
                        dismissLoading()
                        if (t.data == null) return
                        if (t.code == 200) {
                            if (type == MODEL_IMG) {
                                fileParamUrl.set(t.data?.url)
                                val bean : ImgRspBean = t.data!!
                                val fileBean = FileBean()
                                fileBean.url = bean.url
                                fileBean.fileUrl = bean.url
                                fileBean.name = bean.name
                                fileBean.fileName = bean.name
                                var list : MutableList<FileBean> = arrayListOf()
                                list.add(fileBean)
                                fileList = list
                            } else if (type == ADAPTER_IMG) {
                                uc.choiceAdapterFileEvent.postValue(t.data)
                            }
                        } else {
                            showErrorToast(t.msg)
                        }
                    }

                    override fun onFailed(msg: String?) {
                        dismissLoading()
                        showErrorToast(msg)
                    }

                })
        }
    }
    fun checkBeanInfo(): Boolean {
        if (entityBean.parentCompanyId == null) {
            showNormalToast("请选择产权公司！")
            return true
        }
        if (entityBean.facilityType == null) {
            showNormalToast("请选择资产类型！")
            return true
        }
        return false
    }
    fun checkListInfo(): Boolean {
        var isReturn = false
        if (entityBean.facilityType == 0) {
            for (bean in facilityList){
                if (bean.reason == null) bean.reason = ""
                if (bean.planAssetType == null) {
                    showNormalToast("请选择拟处置方式！")
                    isReturn = true
                    break
                }
                if (bean.reasonClassification == null) {
                    showNormalToast("请选择处置原因！")
                    isReturn = true
                    break
                }
            }
        } else {

            for (bean in inUseLowerList){
                if (bean.planAssetType == null) {
                    showNormalToast("请选择拟处置方式！")
                    isReturn = true
                    break
                }
            }
            for (bean in inStoreLowerList){
                if (bean.planAssetType == null) {
                    showNormalToast("请选择拟处置方式！")
                    isReturn = true
                    break
                }
            }
            for (bean in inUseProductList){
                if (bean.planAssetType == null) {
                    showNormalToast("请选择拟处置方式！")
                    isReturn = true
                    break
                }
            }
            for (bean in inStoreProductList){
                if (bean.planAssetType == null) {
                    showNormalToast("请选择拟处置方式！")
                    isReturn = true
                    break
                }
            }
        }
        return isReturn
    }

    fun getCompanyList(
    ) {
        model.mTengYunHttpDataSource.selectCompanyByModule(
            GsonUtils.toJson(
                mapOf(
                    "userId" to model.getLocalUserInfo()?.userId
                )
            )
        ).compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriberHelper<BaseBean<ListBean<CompanyBean>>>() {
                override fun onResult(t: BaseBean<ListBean<CompanyBean>>) {
                    if (t.state == 0) {
                        uc.choiceOwnerCompanyListEvent.postValue(t.data)
                    } else {
                        showNormalToast(t.msg)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }
            })
    }

    fun addApply() {
        entityBean.handleType = 1
        model.mTengYunHttpDataSource.addAssetApplication(
            GsonUtils.toJson(
                entityBean
            )
        ).compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriberHelper<BaseBean<AssetHandleBean>>() {
                override fun onResult(t: BaseBean<AssetHandleBean>) {
                    if (t.state == 0) {
                        var msg = "提交审核成功"
                        if (entityBean.type == 0) {
                            msg = "保存成功"
                        }
                        showNormalToast(msg)
                        clearEntityBean()
                        LiveBusCenter.postGoToTabEvent(1)
//                        t.data
                    } else {
                        showNormalToast(t.msg)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }
            })
    }

    fun clearEntityBean() {
        entityBean = AssetHandleBean()
        entityBeanNote.set("")
        fileParamUrl.set("")
        facilityTypeStr.set("请选择资产类型")
        ownerCompanyStr.set("请选择产权公司")

        uc.clearFacilityListEvent.postValue(0)
        uc.clearLowerListEvent.postValue(0)
    }
}